package com.meowcook.service.impl;

import com.meowcook.common.AppResult;
import com.meowcook.common.ResultCode;
import com.meowcook.dao.*;
import com.meowcook.exception.AppException;
import com.meowcook.mapper.CookerPojoMapper;
import com.meowcook.mapper.CookingPojoMapper;
import com.meowcook.mapper.MaterialPojoMapper;
import com.meowcook.mapper.RecipePojoMapper;
import com.meowcook.pojo.dto.RecipeAddDTO;
import com.meowcook.pojo.dto.RecipeUpdateDTO;
import com.meowcook.pojo.po.*;
import com.meowcook.pojo.vo.RecipeDetailVO;
import com.meowcook.pojo.vo.RecipePartIVO;
import com.meowcook.service.IRecipeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28792
 * Date: 2025-05-03
 * Time: 19:14
 */
@Slf4j
@Service
public class RecipeServiceImpl implements IRecipeService {
    @Resource
    private RecipeMapper recipeMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private CookerMapper cookerMapper;
    @Resource
    private CookingMapper cookingMapper;
    @Resource
    private MaterialMapper materialMapper;
    @Resource
    private RecipePojoMapper recipePojoMapper;
    @Resource
    private CookingPojoMapper cookingPojoMapper;
    @Resource
    private CookerPojoMapper cookerPojoMapper;
    @Resource
    private MaterialPojoMapper materialPojoMapper;

    @Override
    public void createOneRecipe(RecipeAddDTO recipeAddDTO, Long userId) {
        // 数据转化
        Recipe recipe = recipePojoMapper.toPO(recipeAddDTO);

        // 为recipe设置默认值
        recipe.setUserId(userId);
        recipe.setLikeCount(0);
        recipe.setCollectCount(0);
        recipe.setCommentCount(0);
        recipe.setIsApproved((byte) 0);
        recipe.setIsDeleted((byte) 0);
        Date date = new Date();
        recipe.setCreateTime(date);
        recipe.setUpdateTime(date);

        // 调用dao
        int row = recipeMapper.insertSelective(recipe);
        if (row != 1) {
            log.info("新增食谱recipe失败");
            throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        }

        // 获取关联属性对象
        List<Cooking> cookingList = cookingPojoMapper.toPO(recipeAddDTO.getCookingDTOS());
        List<Cooker> cookerList = cookerPojoMapper.toPO(recipeAddDTO.getCookerDTOS());
        List<Material> materialList = materialPojoMapper.toPO(recipeAddDTO.getMaterialDTOS());

        // 为关联属性对象设置默认值并调用dao
        for (Cooking c : cookingList) {
            c.setRecipeId(recipe.getId());
            c.setIsDeleted((byte) 0);
            c.setCreateTime(date);
            c.setUpdateTime(date);
            int r = cookingMapper.insertSelective(c);
            if (r != 1) {
                log.info("新增食谱cooking失败");
                throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
            }
        }
        for (Cooker c : cookerList) {
            c.setRecipeId(recipe.getId());
            c.setIsDeleted((byte) 0);
            c.setCreateTime(date);
            c.setUpdateTime(date);
            int r = cookerMapper.insertSelective(c);
            if (r != 1) {
                log.info("新增食谱cooker失败");
                throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
            }
        }
        for (Material m : materialList) {
            m.setRecipeId(recipe.getId());
            m.setIsDeleted((byte) 0);
            m.setCreateTime(date);
            m.setUpdateTime(date);
            int r = materialMapper.insertSelective(m);
            if (r != 1) {
                log.info("新增食谱material失败");
                throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
            }
        }
        User user = userMapper.selectByPrimaryKey(userId);
        Integer count = user.getRecipeCount() + 1;
        user = new User();
        user.setId(userId);
        user.setRecipeCount(count);
        row = userMapper.updateByPrimaryKeySelective(user);
        if (row != 1) {
            log.info("更新用户recipeCount失败");
            throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        }

    }

    @Override
    public List<RecipePartIVO> selectByBoardId(Long boardId, Integer offset, Integer limit) {
        List<Recipe> recipes = recipeMapper.selectByBoardId(boardId, offset, limit);
        return recipePojoMapper.toPartIVO(recipes);
    }

    @Override
    public RecipeDetailVO selectDetailByRecipeId(Long recipeId) {
        Recipe recipe = recipeMapper.selectDetailByRecipeId(recipeId);
        return recipePojoMapper.toDetailVO(recipe);
    }

    @Override
    public void updateRecipe(RecipeUpdateDTO recipeUpdateDTO) {
        // 数据转化
        Recipe recipe = recipePojoMapper.toPO(recipeUpdateDTO.getRecipeDTO());
        List<Cooking> cookingUpdateList = cookingPojoMapper.updateToPO(recipeUpdateDTO.getCookingUpdateList());
        List<Cooker> cookerUpdateList = cookerPojoMapper.updateToPO(recipeUpdateDTO.getCookerUpdateList());
        List<Material> materialUpdateList = materialPojoMapper.updateToPO(recipeUpdateDTO.getMaterialUpdateList());
        List<Cooking> cookingAddList = cookingPojoMapper.toPO(recipeUpdateDTO.getCookingAddList());
        List<Cooker> cookerAddList = cookerPojoMapper.toPO(recipeUpdateDTO.getCookerAddList());
        List<Material> materialAddList = materialPojoMapper.toPO(recipeUpdateDTO.getMaterialAddList());

        // 更新关联属性对象
        if (recipe != null) {
            recipe.setId(recipeUpdateDTO.getId());
            int row = recipeMapper.updateByPrimaryKeySelective(recipe);
            if (row != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        }

        if (cookingUpdateList != null) {
            for (Cooking c : cookingUpdateList) {
                int r = cookingMapper.updateByPrimaryKeySelective(c);
                if (r != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
            }
        }

        if (cookerUpdateList != null) {
            for (Cooker c : cookerUpdateList) {
                int r = cookerMapper.updateByPrimaryKeySelective(c);
                if (r != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
            }
        }

        if (materialUpdateList != null) {
            for (Material m : materialUpdateList) {
                int r = materialMapper.updateByPrimaryKeySelective(m);
                if (r != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
            }
        }

        // 新增关联属性对象
        Date date = new Date();
        if (cookingAddList != null) {
            for (Cooking c : cookingAddList) {
                c.setRecipeId(recipeUpdateDTO.getId());
                c.setIsDeleted((byte) 0);
                c.setCreateTime(date);
                c.setUpdateTime(date);
                int r = cookingMapper.insertSelective(c);
                if (r != 1) {
                    log.info("新增食谱cooking失败");
                    throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
                }
            }
        }
        if (cookerAddList != null) {
            for (Cooker c : cookerAddList) {
                c.setRecipeId(recipeUpdateDTO.getId());
                c.setIsDeleted((byte) 0);
                c.setCreateTime(date);
                c.setUpdateTime(date);
                int r = cookerMapper.insertSelective(c);
                if (r != 1) {
                    log.info("新增食谱cooker失败");
                    throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
                }
            }
        }
        if (materialAddList != null) {
            for (Material m : materialAddList) {
                m.setRecipeId(recipeUpdateDTO.getId());
                m.setIsDeleted((byte) 0);
                m.setCreateTime(date);
                m.setUpdateTime(date);
                int r = materialMapper.insertSelective(m);
                if (r != 1) {
                    log.info("新增食谱material失败");
                    throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
                }
            }
        }

    }

    @Override
    public void deleteRecipe(Long recipeId) {
        Recipe recipe = recipeMapper.selectByPrimaryKey(recipeId);
        if (recipe == null && recipe.getIsDeleted() == 1) {
            log.info("食谱不存在或已被删除");
            throw new AppException(AppResult.fail("食谱不存在或已删除"));
        }
        Recipe updateRecipe = new Recipe();
        updateRecipe.setId(recipeId);
        updateRecipe.setIsDeleted((byte) 1);
        int row = recipeMapper.updateByPrimaryKeySelective(updateRecipe);
        if (row != 1) {
            log.info("食谱删除失败！");
            throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        }
        User user = userMapper.selectByPrimaryKey(recipe.getUserId());
        int count = user.getRecipeCount() - 1;
        user = new User();
        user.setId(recipe.getUserId());
        user.setRecipeCount(count);
        row = userMapper.updateByPrimaryKeySelective(user);
        if (row != 1) {
            log.info("用户删除食谱数量失败！");
            throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        }

    }

    @Override
    public List<RecipePartIVO> selectByUserId(Long userId, Integer offset, Integer limit) {
        List<Recipe> recipes = recipeMapper.selectByUserId(userId, offset, limit);
        return recipePojoMapper.toPartIVO(recipes);
    }

    @Override
    public List<RecipePartIVO> selectCollectionByUserId(Long userId, Integer offset, Integer limit, Integer blocked) {
            List<Recipe> list = recipeMapper.selectCollectionByUserId(userId, offset, limit, blocked);
        return recipePojoMapper.toPartIVO(list);
    }
}
